package caseCalNumOfSignal;

import org.junit.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 李泽伟
 */
public class MainTest {
    @Test
    public void test()  {
        //统计文件中各个字符出现的次数
        HashMap<Character, Integer> hashMap = new HashMap<>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(new File("hello.txt")));
            char[] buf = new char[10];
            int len;
            while ((len = reader.read(buf))!=-1){
                for(int i=0;i<len;i++){
                    if(!hashMap.containsKey(buf[i])){
                        hashMap.put(buf[i], 1);
                    }else {
                        hashMap.put(buf[i], hashMap.get(buf[i])+1);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Set<Map.Entry<Character, Integer>> set = hashMap.entrySet();
        for (Map.Entry<Character, Integer> entry : set) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }

    @Test
    public void test1() throws IOException {
        //1.InputStreamReader字节输入流 -> 字符输入流
        //2.OutputStreamWriter字符输出流 -> 字节输出流
        FileInputStream inputStream = new FileInputStream("hello.txt");
        //3.参数2取决于保存文件时用的编码字符集， 以编码方式读取字节流数据并转换为字符流数据
        InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        //4.以指定编码方式保存字符流数据
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("helloSet.txt"), "gbk");
        char[] chars = new char[10];
        int len;
        while ((len = reader.read(chars)) != -1) {
            String str = new String(chars, 0, len);
            System.out.print(str);
            writer.write(str);
        }
        writer.close();
        reader.close();
    }

}
